// swagger 文档
defineRouteMeta({
  openAPI: {
    description: 'IP定位',
    summary: 'IP定位',
    tags: ['IP定位'],

    responses: {
      200: {
        description: 'IP定位',
        content: {
          'application/json': {
            schema: {
              type: 'object',
              properties: {
                asn: {
                  type: 'string',
                  description: 'ASN'
                },
                countryName: {
                  type: 'string',
                  description: '国家名称',
                  example: 'China'
                },
                countryCodeAlpha2: {
                  type: 'string',
                  description: '国家代码',
                  example: 'CN'
                },
                countryCodeNumeric: {
                  type: 'string',
                  description: '国家代码',
                  example: '156'
                },
                regionName: {
                  type: 'string',
                  description: '省/市名称',
                  example: 'Zhejiang'
                },
                regionCode: {
                  type: 'string',
                  description: '省/市代码',
                  example: 'CN-ZJ'
                },
                cityName: {
                  type: 'string',
                  description: '城市名称',
                  example: 'Hangzhou'
                },
                latitude: {
                  type: 'string',
                  description: '纬度',
                  example: 30.26
                },
                longitude: {
                  type: 'string',
                  description: '经度',
                  example: 120.13
                },
                cisp: {
                  type: 'string',
                  description: '运营商',
                  example: '中国电信'
                }
              }
            }
          }
        }
      }
    }
  }
});

export default defineEventHandler(async event => {
  // ... 在这里做任何你想做的事情
  const headers = event.node.req.headers['eo-connecting-geo'] as string | undefined;
  let h: Record<string, string> = {};
  if (!headers) {
    return {
      ip: event.node.req.headers['eo-connecting-ip']
    };
  }

  //headers url解码
  h = decodeURIComponent(headers)
    .replaceAll('"', '')
    .split(' ')
    .reduce((acc: Record<string, string>, cur) => {
      const [key, value] = cur.split('=');
      acc[key] = value;
      return acc;
    }, {});

  return {
    ip: event.node.req.headers['eo-connecting-ip'],
    asn: h.asn,
    countryName: h.nation_name,
    countryCodeAlpha2: h.nation_alpha2,
    countryCodeNumeric: h.nation_numeric,
    regionName: h.region_name,
    regionCode: h.region_code,
    cityName: h.city_name,
    latitude: h.latitude,
    longitude: h.longitude,
    cisp: h.network_operator
  };
});
